<template>
  <div class="retail-return-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchForm.returnNo" style="width: 240px; padding-right: 15px;" placeholder="请输入退货单号" />
      <el-input v-model="searchForm.outboundNo" style="width: 240px; padding-right: 15px;" placeholder="请输入出库单号" />
      <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
        <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
      </el-select>
      <el-icon @click="handleSearch()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearch()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">新增零售退货</el-button>
    </div>

    <!-- 零售退货表格 -->
    <el-table :data="tableData" style="width: 100%" stripe border="true" v-loading="loading">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
      <el-table-column prop="returnNo" label="退货单号" width="180" align="center" />
      <el-table-column prop="outboundNo" label="出库单号" width="180" align="center" />
      <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
      <el-table-column prop="returnDate" label="退货日期" width="150" align="center">
        <template #default="scope">{{ formatDateYMD(scope.row.returnDate) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" #default="scope" align="center">
        <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
        <span v-if="scope.row.status == 1" style="color: blue;">待完成</span>
        <span v-if="scope.row.status == 2" style="color: green;">已完成</span>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" align="center" />
      <el-table-column label="操作" width="300px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="viewRetailReturnDetails(scope.row.id)">详情</el-button>
        <el-button type="warning" plain @click="showEditDialog(scope.row)" v-if="scope.row.status === 0">修改</el-button>
        <el-button type="success" plain @click="onCompleteRetailReturn(scope.row.id)" v-if="scope.row.status === 1">完成退货</el-button>
        <el-button type="danger" plain @click="onDeleteRetailReturn(scope.row.id)" v-if="scope.row.status === 0">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑零售退货' : '新增零售退货'" width="1150px" :before-close="handleDialogClose" :close-on-click-modal="false" style="left: 90px">
      <el-form :model="retailReturn" :rules="rules" ref="formRef" label-width="120px" style="padding: 15px 0;">
        <el-form-item label="退货单号" prop="returnNo" v-if="isEdit">
          <el-input v-model="retailReturn.returnNo" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="出库单号" prop="outboundId">
          <el-select v-model="retailReturn.outboundId" placeholder="请选择出库单" clearable style="width: 100%" @change="onOutboundChange">
            <el-option v-for="outbound in outboundList" :key="outbound.id" :label="outbound.outboundNo" :value="outbound.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="retailReturn.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
            <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="退货日期" prop="returnDate">
          <el-date-picker v-model="retailReturn.returnDate" type="date" placeholder="请选择退货日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="退货状态" prop="status" v-if="isEdit">
          <el-select v-model="retailReturn.status" placeholder="请选择退货状态" style="width: 100%">
            <el-option label="草稿" :value="0" />
            <el-option label="待完成" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="retailReturn.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="items-container">
            <div class="items-header">
              <h4>退货商品明细</h4>
              <el-button type="primary" size="small" @click="addItem">添加商品</el-button>
            </div>
            <el-table :data="retailReturn.items || []" style="width: 100%" stripe border="true">
              <el-table-column label="序号" width="60px" #default="scope" align="center">{{ scope.$index + 1 }}</el-table-column>
              <el-table-column label="产品名称" width="200px">
                <template #default="scope">
                  <div v-if="isEdit && scope.row.productId && scope.row.productName">
                    <span>{{ scope.row.productName }}</span>
                    <el-button type="text" size="small" @click="editProduct(scope.row)" style="margin-left: 10px;">修改</el-button>
                  </div>
                  <el-select v-else v-model="scope.row.productId" placeholder="请选择产品" @change="onProductChange(scope.row)">
                    <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="150px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :step="1" @change="calculateTotal" />
                </template>
              </el-table-column>
              <el-table-column label="单价" width="150px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" :step="0.01" @change="calculateTotal" />
                </template>
              </el-table-column>
              <el-table-column label="小计" width="120px" align="center">
                <template #default="scope">¥{{ ((scope.row.quantity || 0) * (scope.row.unitPrice || 0)).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column label="备注" width="150px">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose" size="default">取消</el-button>
          <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 零售退货详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="零售退货详情" width="800px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
      <div v-if="currentRetailReturn" class="retail-outbound-detail">
        <div class="detail-header">
          <p><span class="label">退货单号：</span>{{ currentRetailReturn.returnNo }}</p>
          <p><span class="label">出库单号：</span>{{ currentRetailReturn.outboundNo }}</p>
          <p><span class="label">仓库名称：</span>{{ currentRetailReturn.warehouseName }}</p>
          <p><span class="label">退货日期：</span>{{ formatDateYMD(currentRetailReturn.returnDate) }}</p>
          <p><span class="label">退货状态：</span>
            <span v-if="currentRetailReturn.status == 0" style="color: gray;">草稿</span>
            <span v-if="currentRetailReturn.status == 1" style="color: blue;">待完成</span>
            <span v-if="currentRetailReturn.status == 2" style="color: green;">已完成</span>
          </p>
          <p><span class="label">备注：</span>{{ currentRetailReturn.remark }}</p>
        </div>

        <div class="detail-items">
          <h3>商品明细</h3>
          <el-table :data="currentRetailReturn.items || []" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">{{ scope.$index + 1 }}</el-table-column>
            <el-table-column prop="productName" label="产品名称" width="180" align="center" />
            <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
            <el-table-column prop="quantity" label="数量" width="120" align="center" />
            <el-table-column prop="unitPrice" label="单价" width="120" align="center">
              <template #default="scope">¥{{ scope.row.unitPrice }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="小计" width="120" align="center">
              <template #default="scope">¥{{ scope.row.amount }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="120" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import {
  getRetailReturnPage,
  createRetailReturn,
  updateRetailReturn,
  deleteRetailReturn as deleteRetailReturnApi,
  completeRetailReturn as completeRetailReturnApi,
  getRetailReturnWithDetails
} from '@/api/retail/retail_return'
import { getRetailOutboundPage, getRetailOutboundWithDetails } from '@/api/retail/retail_outbound'
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse'

export default {
  name: 'RetailReturn',
  setup() {
    // 工具函数：日期格式化仅显示 YYYY-MM-DD
    function formatDateYMD(value) {
      if (!value) return ''
      if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value
      if (typeof value === 'string') {
        const m = value.match(/^(\d{4}-\d{2}-\d{2})/)
        if (m) return m[1]
      }
      try {
        const d = new Date(value)
        if (!isNaN(d.getTime())) {
          const y = d.getFullYear()
          const mm = String(d.getMonth() + 1).padStart(2, '0')
          const dd = String(d.getDate()).padStart(2, '0')
          return `${y}-${mm}-${dd}`
        }
      } catch (_) {}
      return String(value)
    }

    // 响应式数据
    const loading = ref(false)
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)
    const currentRetailReturn = ref(null)

    // 搜索表单
    const searchForm = reactive({
      returnNo: '',
      outboundNo: '',
      warehouseId: null,
      startDate: '',
      endDate: ''
    })

    // 分页（与出库一致）
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 零售退货数据
    const retailReturn = ref({
      id: null,
      returnNo: '',
      outboundId: null,
      warehouseId: null,
      returnDate: '',
      totalAmount: 0,
      status: 0,
      remark: '',
      items: []
    })

    // 列表数据
    const tableData = ref([])
    const warehouseList = ref([])
    const productList = ref([])
    const outboundList = ref([])

    // 表单验证规则（与出库一致）
    const rules = {
      outboundId: [{ required: true, message: '请选择出库单', trigger: 'change' }],
      warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
      returnDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }]
    }

    // 计算属性
    const dialogTitle = computed(() => (isEdit.value ? '编辑零售退货' : '新增零售退货'))

    // 加载列表
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          returnNo: searchForm.returnNo,
          warehouseId: searchForm.warehouseId,
          startDate: searchForm.startDate,
          endDate: searchForm.endDate
        }
        const page = await getRetailReturnPage(params)
        // request 拦截器已返回 data，直接取 records/total
        tableData.value = Array.isArray(page?.records) ? page.records : []
        pagination.total = Number(page?.total) || tableData.value.length || 0
        
        // 调试日志：检查数据是否正确加载
        console.log('零售退货列表数据已刷新:', tableData.value)
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const loadWarehouseList = async () => {
      try {
        const data = await getWarehouseList()
        warehouseList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载仓库列表失败:', error)
      }
    }

    const loadProductList = async () => {
      try {
        const data = await getProductList()
        productList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载商品列表失败:', error)
      }
    }

    const loadOutboundList = async () => {
      try {
        const page = await getRetailOutboundPage({ pageNum: 1, pageSize: 100 })
        outboundList.value = Array.isArray(page?.records) ? page.records : []
      } catch (error) {
        console.error('加载出库单列表失败:', error)
      }
    }

    const handleSearch = () => {
      pagination.pageNum = 1
      loadData()
    }

    const resetSearch = () => {
      Object.assign(searchForm, { returnNo: '', outboundNo: '', warehouseId: null, startDate: '', endDate: '' })
      pagination.pageNum = 1
      loadData()
    }

    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadData()
    }

    const handleCurrentChange = (val) => {
      pagination.pageNum = val
      loadData()
    }

    const showAddDialog = () => {
      isEdit.value = false
      retailReturn.value = {
        id: null,
        returnNo: undefined,
        outboundId: null,
        warehouseId: null,
        returnDate: new Date().toISOString().split('T')[0],
        totalAmount: 0,
        status: 0,
        remark: '',
        items: []
      }
      dialogVisible.value = true
      if (formRef.value) formRef.value.resetFields()
    }

    const showEditDialog = async (row) => {
      isEdit.value = true
      dialogVisible.value = true
      try {
        const data = await getRetailReturnWithDetails(row.id)
        retailReturn.value = data || { ...row, items: [] }
      } catch (error) {
        console.error('获取零售退货详情失败:', error)
        ElMessage.error('获取零售退货详情失败')
        retailReturn.value = { ...row, items: [] }
      }
    }

    const handleDialogClose = () => {
      dialogVisible.value = false
      retailReturn.value = {
        id: null,
        returnNo: '',
        outboundId: null,
        warehouseId: null,
        returnDate: '',
        totalAmount: 0,
        status: 0,
        remark: '',
        items: []
      }
      if (formRef.value) formRef.value.resetFields()
    }

    const addItem = () => {
      if (!retailReturn.value.items) retailReturn.value.items = []
      retailReturn.value.items.push({
        productId: null,
        productName: null,
        productCode: null,
        quantity: 1,
        unitPrice: 0,  // 改为 unitPrice
        remark: ''
      })
    }

    const removeItem = (index) => {
      retailReturn.value.items.splice(index, 1)
      calculateTotal()
    }

    const editProduct = (item) => {
      item.productId = null
      item.productName = null
      item.productCode = null
    }

    const onProductChange = (item) => {
      const product = productList.value.find(p => p.id === item.productId)
      if (product) {
        item.productName = product.name
        item.productCode = product.code
        // 可选：默认价格
        if (!item.unitPrice || item.unitPrice === 0) item.unitPrice = product.price || 0  // 改为 unitPrice
      }
      calculateTotal()
    }

    const onOutboundChange = async (outboundId) => {
      if (!outboundId) return
      try {
        const outbound = await getRetailOutboundWithDetails(outboundId)
        // 如果未选择仓库，则以出库单仓库为默认
        if (outbound?.warehouseId && !retailReturn.value.warehouseId) {
          retailReturn.value.warehouseId = outbound.warehouseId
        }
        // 用出库明细填充退货明细（可手动改数量）
        const items = Array.isArray(outbound?.items) ? outbound.items : []
        retailReturn.value.items = items.map(i => ({
          productId: i.productId,
          productName: i.productName,
          productCode: i.productCode,
          quantity: i.quantity, // 默认整单退回，可手动调整
          unitPrice: i.unitPrice || 0,  // 改为 unitPrice
          remark: ''
        }))
        calculateTotal()
      } catch (e) {
        console.error('加载出库单详情失败:', e)
        ElMessage.error('加载出库单明细失败')
      }
    }

    const calculateTotal = () => {
      let total = 0
      if (retailReturn.value.items?.length) {
        retailReturn.value.items.forEach(item => {
          total += (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0)  // 改为 unitPrice
        })
      }
      retailReturn.value.totalAmount = Number(total.toFixed(2))
    }

    const submitForm = async () => {
      if (!formRef.value) return
      try {
        await formRef.value.validate()

        if (!retailReturn.value.items || retailReturn.value.items.length === 0) {
          ElMessage.warning('请至少添加一个商品')
          return
        }

        // 生成提交数据并做字段转换（确保字段名正确）
        const convertItems = (items) =>
          items.map(it => ({
            id: it.id, // 如果没有 id，让后端自增
            productId: it.productId,
            quantity: it.quantity,
            unitPrice: it.unitPrice,  // 直接使用 unitPrice
            amount: Number(((Number(it.quantity)||0) * (Number(it.unitPrice)||0)).toFixed(2)),  // 使用 unitPrice
            remark: it.remark
          }))

        if (isEdit.value) {
          const updateData = { ...retailReturn.value }
          updateData.items = convertItems(updateData.items)
          // 日期标准化
          if (updateData.returnDate) updateData.returnDate = formatDateYMD(updateData.returnDate)
          const updatedData = await updateRetailReturn(updateData)
          ElMessage.success('更新成功')
          
          // 立即更新本地数据，确保状态显示正确
          if (updatedData) {
            // 更新表格中对应的行数据
            const index = tableData.value.findIndex(item => item.id === updatedData.id)
            if (index !== -1) {
              tableData.value[index] = { ...tableData.value[index], ...updatedData }
            }
          }
        } else {
          const createData = { ...retailReturn.value }
          // 创建时移除所有ID相关字段，让后端处理
          delete createData.id
          delete createData.returnNo
          // 确保明细项也没有ID相关字段
          createData.items = convertItems(createData.items).map(item => {
            const newItem = { ...item }
            delete newItem.id
            delete newItem.returnId
            return newItem
          })
          if (createData.returnDate) createData.returnDate = formatDateYMD(createData.returnDate)
          await createRetailReturn(createData)
          ElMessage.success('创建成功')
        }

        dialogVisible.value = false
        // 强制刷新列表数据
        await loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交失败:', error)
          ElMessage.error('提交失败')
        }
      }
    }

    const onDeleteRetailReturn = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个零售退货单吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        await deleteRetailReturnApi(id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const onCompleteRetailReturn = async (id) => {
      try {
        await ElMessageBox.confirm('确定要完成这个零售退货单吗？完成后将自动调整库存。', '完成确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        await completeRetailReturnApi(id)
        ElMessage.success('完成成功，库存已调整')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('完成失败:', error)
          ElMessage.error('完成失败')
        }
      }
    }

    const viewRetailReturnDetails = async (id) => {
      try {
        const data = await getRetailReturnWithDetails(id)
        currentRetailReturn.value = data || null
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取零售退货详情失败:', error)
        ElMessage.error('获取零售退货详情失败')
      }
    }

    const handleDetailDialogClose = () => {
      detailDialogVisible.value = false
      currentRetailReturn.value = null
    }

    onMounted(() => {
      loadData()
      loadWarehouseList()
      loadProductList()
      loadOutboundList()
    })

    return {
      // 数据
      loading,
      dialogVisible,
      detailDialogVisible,
      isEdit,
      formRef,
      currentRetailReturn,
      searchForm,
      pagination,
      retailReturn,
      tableData,
      warehouseList,
      productList,
      outboundList,
      rules,
      dialogTitle,
      // 方法
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      showAddDialog,
      showEditDialog,
      handleDialogClose,
      addItem,
      removeItem,
      editProduct,
      onProductChange,
      onOutboundChange,
      calculateTotal,
      submitForm,
      onDeleteRetailReturn,
      onCompleteRetailReturn,
      viewRetailReturnDetails,
      handleDetailDialogClose,
      formatDateYMD
    }
  }
}
</script>

<style scoped>
.retail-return-container {
  padding: 20px;
}

.search-bar {
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-input,
.search-bar .el-select,
.search-bar .el-date-picker {
  margin-right: 15px;
}

.search-bar .el-button {
  margin-left: 15px;
}

.retail-outbound-detail {
  padding: 10px;
}

.detail-header { margin-bottom: 20px; }
.detail-header p { margin: 8px 0; }
.label { font-weight: bold; display: inline-block; width: 100px; }
.detail-items h3 { margin-bottom: 10px; }

.dialog-footer { display: flex; justify-content: flex-end; gap: 10px; }

.items-container { border: 1px solid #e4e7ed; border-radius: 4px; padding: 15px; }
.items-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding: 10px 0; border-bottom: 1px solid #e4e7ed; }
.items-header h4 { margin: 0; color: #409eff; font-size: 16px; font-weight: 600; }
</style>
